<template>
  <div class="attribute-panel" :class="card ? 'attribute-panel-card' : ''">
    <el-collapse class="panel" v-model="activeName" accordion>
      <el-collapse-item :title="title" name="1">
        <template #title>
          <div class="panel-title-label">{{ title }}</div>
          <div class="panel-title" @click.stop v-if="options">:
            <el-cascader v-model="id" :class="err ? 'title-err' : ''" :placeholder="`请选择${title}!`" :options="options"
              style="width: 100%" :props="{ label: 'typeName', value: 'id', multiple: false, emitPath: false }" clearable
              @change="changeMT"></el-cascader>
          </div>
        </template>
        <slot>
          <slot name="before"></slot>
          <el-row :gutter="20" v-for="(row, i) in rowsData" :key="i">
            <el-col v-for="(col, j) in row" :key="j" :span="col.span">
              <el-form-item :label="col.data.specsName" label-width="80px"
                :rules="{ required: true, validator: (e1, e2, cb) => validator(col.data, cb) }" prop="specsList">
                <el-select style="width: 100%;" v-model="col.data.value" :placeholder="`请选择 ${col.data.specsName}`"
                  @change="refresh" :key="updateKey" filterable allow-create>
                  <el-option v-for="(li, j) in col.data.list" :key="j" :label="li.val" :value="li.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <slot name="after"></slot>
        </slot>
      </el-collapse-item>
      <i class="el-icon-circle-plus panel-add panel-icon" v-if="add" @click="$emit('add')"></i>
      <i class="el-icon-remove  panel-remove panel-icon" v-if="remove" @click="$emit('remove')"></i>
    </el-collapse>
  </div>
</template>

<script>
import { getSpecsListFromMaterial } from "@/api/data/specs";
export default {
  props: {
    mtid: {
      default: ''
    },
    attrs: {
      default() {
        return ''
      }
    },
    col: {
      default: 2
    },
    title: {
      default: '属性面板'
    },
    expand: {
      default: false
    },
    add: {
      default: false
    },
    remove: {
      default: false
    },
    card: {
      default: false
    },
    options: {
      default() {
        return null
      }
    },
    idKey: {
      default: 'stvalId'
    }
  },
  computed: {
    rows() {
      const rows = []
      for (let i = 0; i < this.materialOptions.length; i += this.col) {
        let j = 0;
        const col = []
        const span = 24 / this.col
        while (j < this.col) {
          const index = i * this.col + j
          if (index >= this.materialOptions.length) break
          const item = { data: this.materialOptions[index], row: rows.length, col: j, span }
          col.push(item)
          j++
        }
        rows.push(col)
      }
      return rows
    },
    mtValues() {
      if (!this.attrs) return []

      return this.attrs.split(',').map(s => s * 1)
    }
  },
  data() {
    return {
      materialOptions: [],
      activeName: '0',
      updateKey: 0,
      id: '',
      rowsData: [],
      err: false
    }
  },
  watch: {
    mtid: {
      handler(val) {
        if (!val) return
        this.id = val
        this.changeMT(val)
      },
      immediate: true,
      deep: true
    },
    rows: {
      handler(val) {
        this.rowsData = JSON.parse(JSON.stringify(val))

        this.emitIds()
      },
      immediate: true,
      deep: true
    },
    expand: {
      handler() {
        this.activeName = this.expand ? '1' : '0'
      },
      immediate: true,
      deep: true
    },
  },
  methods: {
    validator(item, cb) {
      item.value ? cb() : cb(new Error(`请选择 ${item.specsName}`))
    },
    emitIds() {
      const ids = []
      this.rowsData.forEach(r => {
        r.forEach(c => ids.push(c.data.value))
      })

      if (ids.length === this.materialOptions.length) this.$emit('change', ids)
    },
    refresh() {
      this.updateKey++

      this.emitIds()
    },
    changeMT(mtid) {
      this.validate()
      if (!mtid) return this.materialOptions = []
      getSpecsListFromMaterial({ mtid }).then(res => {
        res.data.forEach((row, i) => {
          row.value = this.mtValues[i]
        })
        this.materialOptions = res.data
      })
    },
    validate() {

      this.err = this.id ? false : true

      return !this.err
    },
    getData() {
      if (this.validate() === false) return

      const options = []
      this.rowsData.map(cols => {
        options.push(...cols.map(col => col.data))
      })
      const list = options.map(item => {
        const value = item.list.find(li => li.id === item.value)
        if (value) return { ...value, [this.idKey]: value.id }

        return { [this.idKey]: '', specsId: item.specsId, val: item.value }
      })

      return {
        id: this.id,
        list,
      }
    },
    reset() {
      this.err = false
      this.id = ''
      this.materialOptions = []
    }
  }
}
</script>

<style lang="scss" scoped>
.attribute-panel {
  .panel {
    border-left: 1px solid #e6ebf5;
    border-right: 1px solid #e6ebf5;
    position: relative;
    top: 0;
    left: 0;
    border-bottom-color: transparent;
  }

  .panel-icon {
    font-size: 22px;
    position: absolute;
    top: 25px;
    cursor: pointer;
  }

  .panel-add {
    left: -10px;
    color: #009688;
    transform: translate(-100%, -50%);
  }

  .panel-remove {
    right: -10px;
    color: #e41c1c;
    transform: translate(100%, -50%);
  }

  ::v-deep .el-collapse-item__header {
    padding: 0 20px;
    background-color: #f5f5f5;
    font-size: 14px;
    color: #009688;
    font-weight: bold;

    .panel-title-label {
      margin-right: 4px;
    }

    .panel-title {
      display: flex;
      align-items: center;
      box-sizing: border-box;


      .el-input__inner {
        background-color: transparent;
        font-size: 12px;
        border-color: transparent;
      }
    }

    .title-err {


      .el-input__inner::placeholder {
        color: #ff4949;
      }
    }
  }

  ::v-deep .el-collapse-item__header.is-active {
    border-bottom: 1px solid #e6ebf5;
  }

  ::v-deep .el-collapse-item__wrap {
    padding: 0 20px;
    background-color: #f5f5f5;

    .el-collapse-item__content {
      padding-top: 20px;
    }

    .el-select {
      width: 100%;
    }

    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
      width: 100%;
    }
  }
}

.attribute-panel-card {

  ::v-deep .el-collapse-item__header {
    background-color: #fff;
    color: #333333;
  }

  ::v-deep .el-collapse-item__wrap {
    background-color: #fff;
  }
}
</style>
